#include<iostream>
#include<string>
#include<cstring>
#include"Log.hpp"
#include<sys/types.h>
#include<sys/socket.h>
#include<cstring>
#include <netinet/in.h>
#include <arpa/inet.h>


//./udpclient ip port
int main(int argc,char* argv[3])
{
    if(argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
        exit(1);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);
    int _socket = socket(AF_INET,SOCK_DGRAM,0);

    if(_socket < 0)
    {
        std :: cerr << "socket error" << std :: endl;
        exit(2);
    }

    //客户端不必和结构体进行bind，因为防止端口的竞争。

    struct sockaddr_in server; //定义好结构体，里面存放服务器相关的数据
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    //开始进入死循环


    while(1)
    {
        std :: string input;
        std :: cout << "Please Enter#";
        std :: getline(std :: cin,input);  //把左边的输入到右边
        //传消息
        int n = sendto(_socket,input.c_str(),input.size(),0,(sockaddr*)&server,sizeof(server));
        (void)n;

        //收消息

        char buffer[1024];
        struct sockaddr_in _peer;
        socklen_t len = sizeof(_peer);
        ssize_t m = recvfrom(_socket,buffer,sizeof(buffer) - 1,0,(sockaddr*)&_peer,&len);
        if(m > 0)
        {
            buffer[m] = '\0';  //记住放入\0
            std :: cout << buffer << std :: endl; 
        }

    }
    
    return 0;
}